package com.shengchang.hu.supervision.UI;

import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.posapi.PosApi;
import android.posapi.PosApi.OnCommEventListener;
import android.posapi.PrintQueue;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.zyapi.CommonApi;

import com.magicrf.uhfreader.UhfReaderDevice;
import com.magicrf.uhfreader.Util;
import com.magicrf.uhfreaderlib.reader.Tools;
import com.magicrf.uhfreaderlib.reader.UhfReader;
import com.shengchang.hu.supervision.Application.App;
import com.shengchang.hu.supervision.R;
import com.shengchang.hu.supervision.ToolBar.InBoundBar;
import com.shengchang.hu.supervision.Utils.BluetoothLeClass;
import com.shengchang.hu.supervision.Utils.Contants;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.InputMismatchException;
import java.util.List;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class PutInActivity extends BaseActivity  implements View.OnClickListener{

    InBoundBar checkedbar;
    TextView yunsongren;
    EditText xiangweightEdit;

    Button printcode;
    LinearLayout readufh;
    LinearLayout readcode;
    private  String scancode;

    private String name;
    private String code;
    private String id;
    /* 读取UFH*/
    private boolean runFlag = true;
    private boolean startFlag = false;
    private boolean connectFlag = false;
    private boolean powerOn = false;
    private String serialPortPath = "/dev/ttyMT2";
    private UhfReader reader;
    private UhfReaderDevice readerDevice;
    static CommonApi mCommonApi;
    private int mComFd = -1;
    private String Uhfdata;
    /*打印功能*/
    Handler mhandle = new Handler();
    private static final String TEMP_INFO = "temp_info";

    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothLeClass mBLE;
    private boolean isLoop = false;
    Handler blemHandler;
    SCALENOW scalenow = new SCALENOW();
    Boolean bisClosed = false;
    private PosApi mPosSDK = null;
    private PrintQueue mPrintQueue = null;


    /*扫描*/
    MediaPlayer player;
    private byte mGpioPower = 0x1E;// PB14
    private byte mGpioTrig = 0x29;// PC9
    boolean isCanPrint = true;

    private int mCurSerialNo = 3; // usart3
    private int mBaudrate = 4; // 9600
    private ScanBroadcastReceiver scanBroadcastReceiver;
    private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;
    private static final String YUNSONG_API = Contants.Yun_Song_API;
    private static final String Terminal_outRubbishInBox_API = Contants.OutRubbishInBox_API;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_put_in);
        checkedbar=findViewById(R.id.checkedbar);
        yunsongren=findViewById(R.id.yunsongren);
        xiangweightEdit=findViewById(R.id.xiangweight_edit);
        printcode=findViewById(R.id.printcode);
        readufh=findViewById(R.id.readufh);
        readcode=findViewById(R.id.readcode);
        checkedbar.setLeftTitleClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {

                    Handler handler = new Handler(Looper.getMainLooper());
                    handler.postDelayed(new Runnable() {
                        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
                        @Override
                        public void run() {

                            initUHF();
                        }
                    },20);
                } catch (InputMismatchException e) {
                    e.printStackTrace();
                }


            }
        }).start();
        initPos();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {

                    Handler handler = new Handler(Looper.getMainLooper());
                    handler.post(new Runnable() {
                        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
                        @Override
                        public void run() {

                            BleSei();


                        }
                    });
                } catch (InputMismatchException e) {
                    e.printStackTrace();
                }


            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {

                    Handler handler = new Handler(Looper.getMainLooper());
                    handler.post(new Runnable() {
                        @Override
                        public void run() {

                            initScan();
                            }
                    });
                } catch (InputMismatchException e) {
                    e.printStackTrace();
                }


            }
        }).start();


        }

    @Override
    protected void onResume() {
        super.onResume();

                new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                // 打开GPIO，给扫描头上电
                openDevice();

            }
        },1000);

    }

    private void initScan() {
        //注册获取扫描信息的广播接收器
        IntentFilter mFilter = new IntentFilter();
        mFilter.addAction(PosApi.ACTION_POS_COMM_STATUS);
        registerReceiver(receiver, mFilter);

        // 物理扫描键按下时候会有动作为ismart.intent.scandown的广播发出，可监听该广播实现触发扫描动作
        scanBroadcastReceiver = new ScanBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("ismart.intent.scandown");
        this.registerReceiver(scanBroadcastReceiver, intentFilter);

        // 扫描提示音
        player = MediaPlayer.create(getApplicationContext(),
                R.raw.beep);

    }

    /**
     * 物理SCAN按键监听
     */
    boolean isScan = false;

    class ScanBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            ScanDomn();

            }
    }

    // 打开串口以及GPIO口
    private void openDevice() {
        // open power
        mPosSDK.gpioControl(mGpioPower, 0, 1);

        mPosSDK.extendSerialInit(mCurSerialNo, mBaudrate, 1, 1, 1, 1);

    }

    /**
     * 执行扫描，扫描后的结果会通过action为PosApi.ACTION_POS_COMM_STATUS的广播发回
     */
    public void ScanDomn() {
        if (!isScan) {
            mPosSDK.gpioControl(mGpioTrig, 0, 0);
            isScan = true;
            handler.removeCallbacks(run);
            // 3秒后还没有扫描到信息则强制关闭扫描头
            handler.postDelayed(run, 3000);
        } else {
            mPosSDK.gpioControl(mGpioTrig, 0, 1);
            mPosSDK.gpioControl(mGpioTrig, 0, 0);
            isScan = true;
            handler.removeCallbacks(run);
            // 3秒后还没有扫描到信息则强制关闭扫描头
            handler.postDelayed(run, 3000);
        }
    }

    Handler handler = new Handler();
    Runnable run = new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            // 强制关闭扫描头
            mPosSDK.gpioControl(mGpioTrig, 0, 1);
            isScan = false;
        }
    };

    /**
     * 扫描信息获取
     */
    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            String action = intent.getAction();
            if (action.equalsIgnoreCase(PosApi.ACTION_POS_COMM_STATUS)) {
                // 串口标志判断
                int cmdFlag = intent.getIntExtra(PosApi.KEY_CMD_FLAG, -1);
                // 获取串口返回的字节数组
                byte[] buffer = intent
                        .getByteArrayExtra(PosApi.KEY_CMD_DATA_BUFFER);
                switch (cmdFlag) {
                    // 如果为扫描数据返回串口
                    case PosApi.POS_EXPAND_SERIAL3:
                        if (buffer == null)
                            return;
                        try {
                            // 将字节数组转成字符串
                            final String str = new String(buffer, "UTF-8");
                            // 开启提示音，提示客户条码或者二维码已经被扫到
                            player.start();
                            if (str != null) {

                                code=str;
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Handler handler = new Handler(Looper.getMainLooper());
                                        handler.post(new Runnable() {
                                            @Override
                                            public void run() {
                                                showProgressDialog();
                                                // 放在UI线程弹Toast
                                                OutRequest();
                                            }
                                        });                //此处会发生异常//
                                    }
                                }).start();

                            } else {
                                showShortToast("扫码失败，请重新扫描");
                            }


                        } catch (UnsupportedEncodingException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        break;
                }
                // 扫描完本次后清空，以便下次扫描
                buffer = null;
            }
        }
    };

    private void initPos() {
        // 获取PosApi实例
        mPosSDK = PosApi.getInstance(this);
        // 根据型号进行初始化mPosApi类
        if (Build.MODEL.contains("LTE")
                || Build.DISPLAY.contains("3508")
                || Build.DISPLAY.contains("403")
                || Build.DISPLAY.contains("35S09")) {
            mPosSDK.initPosDev("ima35s09");
        } else if (Build.MODEL.contains("5501")) {
            mPosSDK.initPosDev("ima35s12");
        } else {
            mPosSDK.initPosDev(PosApi.PRODUCT_MODEL_IMA80M01);
        }

        //监听初始化回调结果
        mPosSDK.setOnComEventListener(mCommEventListener);

    }

    /**
     * 初始化
     */
    OnCommEventListener mCommEventListener = new OnCommEventListener() {
        @Override
        public void onCommState(int cmdFlag, int state, byte[] resp, int respLen) {
            // TODO Auto-generated method stub
            switch (cmdFlag) {
                case PosApi.POS_INIT:
                    if (state == PosApi.COMM_STATUS_SUCCESS) {
                        Toast.makeText(getApplicationContext(), "设备初始化成功",
                                Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(getApplicationContext(), "设备初始化失败",
                                Toast.LENGTH_SHORT).show();
                    }
                    break;
            }
        }
    };


    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.printcode:

                finish();



                break;
        }
    }

    private void OutRequest() {
        OkHttpClient moKhttpclient = new OkHttpClient();
        RequestBody formBody = new FormBody.Builder()
                .add("id", App.getApp().getToken())
                .add("boxCodes", code)
                .add("transoprtId", id)
                .add("handoverName", yunsongren.getText().toString())
                .add("weight",xiangweightEdit.getText().toString())
                .build();
        Request request = new Request.Builder()
                .url(Terminal_outRubbishInBox_API)
                .post(formBody)
                .build();
        Log.d("Terminal", Terminal_outRubbishInBox_API + "?id=" + App.getApp().getToken()
                + "&boxCodes=" + code +
                "&transoprtId=" + id
                + "&handoverName=" + yunsongren.getText().toString()
               +"&weight="+xiangweightEdit.getText().toString());
        Call call = moKhttpclient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Handler handler = new Handler(Looper.getMainLooper());
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                dismissProgressDialog();
                                // 放在UI线程弹Toast
                                showLongToast("请求失败，请确认网络");
                            }
                        });                //此处会发生异常//
                    }
                }).start();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                final String outdata = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        outResquest(outdata);
                    }
                });

            }
        });

    }

    private void outResquest(String outdata) {
        try {
            JSONObject mjson = new JSONObject(outdata);
            String outmsg = mjson.getString("message");
            if (outmsg.equals("20004")) {
                dismissProgressDialog();
                showShortToast("网络连接有错");

            } else if (outmsg.equals("20005")) {
                dismissProgressDialog();
                showShortToast("出库成功");

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void initUHF() {
        SharedPreferences sharedPortPath = getSharedPreferences("portPath", 0);

        serialPortPath = sharedPortPath.getString("portPath", "/dev/ttyMT2");

        mCommonApi = new CommonApi();

        openGPIO();

//        mCommonApi.setGpioDir(78, 1);
//        mCommonApi.setGpioOut(78, 1);
//
//        mCommonApi.setGpioDir(83, 1);
//        mCommonApi.setGpioOut(83, 1);

        mComFd = mCommonApi.openCom(serialPortPath, 115200, 8, 'N', 1);

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                mCommonApi.setGpioDir(53, 1);
                int ret = mCommonApi.setGpioOut(53, 1);
                mCommonApi.setGpioDir(78, 1);
                int ret1 = mCommonApi.setGpioOut(78, 1);
                if (ret == 0) {
//                    Toast.makeText(CollectActivity.this, "卡内信息出错" , Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(PutInActivity.this, "卡外信息出错", Toast.LENGTH_SHORT).show();
                }
            }
        }, 1000);

        UhfReader.setPortPath(serialPortPath);
        reader = UhfReader.getInstance();

        readerDevice = UhfReaderDevice.getInstance();
        if (reader == null) {
            showTipDialog("卡片读取失败");

            return;
        }
        if (readerDevice == null) {

            showTipDialog("校验卡读取失败");

        }
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        SharedPreferences shared = getSharedPreferences("power", 0);
        int value = shared.getInt("value", 26);
        Log.d("", "value" + value);
        reader.setOutputPower(value);

        powerOn = true;


        // TODO Auto-generated method stub
        if (!powerOn) {

            powerOn = true;
            readerDevice.powerOn();

            Toast.makeText(getApplicationContext(), "power On", Toast.LENGTH_LONG).show();

        }


        Thread thread = new InventoryThread();
        thread.start();

        Util.initSoundPool(this);
        if (!startFlag) {
            startFlag = true;

        }
        byte[] versionBytes = reader.getFirmware();
        if (versionBytes != null) {
//				reader.setWorkArea(3);
            Util.play(1, 0);
            String version = new String(versionBytes);

        }
    }

    //rfid卡读取成功之后的网络请求操作和输入框的赋值
    class InventoryThread extends Thread {
        private List<byte[]> epcList;
        @Override
        public void run() {
            super.run();
            while (runFlag) {
                if (startFlag) {
//					reader.stopInventoryMulti()
                    epcList = reader.inventoryRealTime(); //
                    if (epcList != null && !epcList.isEmpty()) {
                        Util.play(1, 0);
                        for (byte[] epc : epcList) {
                            if (epc != null) {

                                final String epcStr = Tools.Bytes2HexString(epc, epc.length);
                                Uhfdata = epcStr;

                                if (!TextUtils.isEmpty(Uhfdata)) {

                                    new Thread(new Runnable() {
                                        @Override
                                        public void run() {

                                            try {

                                                Handler handler = new Handler(Looper.getMainLooper());
                                                handler.post(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        showProgressDialog();
                                                        PutinRequest(Uhfdata);

                                                    }
                                                });
                                            } catch (InputMismatchException e) {
                                                e.printStackTrace();
                                            }

                                        }
                                    }).start();

                                    Log.d("dueha", epcStr);

                                } else {
                                    showShortToast("刷卡失败");
                                }

                                Log.d("ueiqojs", epcStr);
                                if (!Uhfdata.equals("") || Uhfdata != null) {

                                    if (readerDevice != null) {
                                        readerDevice.powerOff();
                                    }
                                    if (mComFd > 0) {
                                        mCommonApi.setGpioDir(78, 1);
                                        mCommonApi.setGpioOut(78, 0);

                                        mCommonApi.setGpioDir(83, 1);
                                        mCommonApi.setGpioOut(83, 0);
                                        mCommonApi.closeCom(mComFd);
                                    }
//
                                }


                            }
                        }
                    }
                    epcList = null;
                    try {
                        Thread.sleep(40);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    private void PutinRequest(String uhfdata) {
        OkHttpClient moKhttp = new OkHttpClient();
        RequestBody formBody = new FormBody.Builder()
                .add("cardCode", uhfdata)
                .build();
        Request request = new Request.Builder()
                .url(YUNSONG_API)
                .post(formBody)
                .build();
        Log.d("YUNSONG_API", YUNSONG_API + "?cardCode=" + uhfdata);
        Call call = moKhttp.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Handler handler = new Handler(Looper.getMainLooper());
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                dismissProgressDialog();
                                // 放在UI线程弹Toast
                                showLongToast("请求失败，请确认网络");
                            }
                        });                //此处会发生异常//
                    }
                }).start();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String Putinstr = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        PutinResponse(Putinstr);
                    }
                });

            }
        });

    }

    private void PutinResponse(String putinstr) {
        try {
            JSONObject putjson = new JSONObject(putinstr);
            String msg = putjson.getString("message");
            if (msg.equals("20004")) {
                dismissProgressDialog();
                showShortToast("网络请求异常");
            } else if (msg.equals("20005")) {
                dismissProgressDialog();
                readufh.setVisibility(View.GONE);
                readcode.setVisibility(View.VISIBLE);

                } else if (msg.equals("20008")) {
                dismissProgressDialog();
                showShortToast("查无此卡");
            } else if (msg.equals("20009")) {
                dismissProgressDialog();
                showShortToast("类型不符合");
            } else if (msg.equals("20019")) {
                dismissProgressDialog();
                showShortToast("卡片未分配");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        try {
            JSONObject putdata = new JSONObject(putinstr);
            String handoverName = putdata.getString("handoverName");
            yunsongren.setText(handoverName);
            if (!TextUtils.isEmpty(yunsongren.getText().toString())) {

                new Thread(new Runnable() {
                    @Override
                    public void run() {

                        try {

                            Handler handler = new Handler(Looper.getMainLooper());
                            handler.post(new Runnable() {
                                @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
                                @Override
                                public void run() {

                                    ConnnectBle();

                                }
                            });
                        } catch (InputMismatchException e) {
                            e.printStackTrace();
                        }


                    }
                }).start();
                JSONObject transportAgency = putdata.getJSONObject("transportAgency");
                name = transportAgency.getString("name");
                id = transportAgency.getString("id");
//                code = transportAgency.getString("code");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    // 打开gpio
    public static void openGPIO() {
        // TODO Auto-generated method stub

        mCommonApi.setGpioDir(78, 1);
        mCommonApi.setGpioOut(78, 1);

        mCommonApi.setGpioDir(83, 1);
        mCommonApi.setGpioOut(83, 1);

        mCommonApi.setGpioDir(68, 1);
        mCommonApi.setGpioOut(68, 1);

    }

    // 关闭gpio
    public static void closeGPIO() {

        mCommonApi.setGpioDir(78, 1);
        mCommonApi.setGpioOut(78, 0);

        mCommonApi.setGpioDir(83, 1);
        mCommonApi.setGpioOut(83, 0);

        mCommonApi.setGpioDir(68, 1);
        mCommonApi.setGpioOut(68, 0);

    }



    private void ConnnectBle() {

        Intent serverIntent = new Intent(PutInActivity.this, DeviceListActivity.class);
        startActivityForResult(serverIntent, 0);
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    @SuppressLint("SimpleDateFormat")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 0:
                if (resultCode == RESULT_OK&& data!=null) {

                    Bundle bundle = data.getExtras();
                    String address = bundle.getString("device_address", "");
                    if (address.length() > 0) {
                        if ((mBLE != null) && mBLE.isConnect) {

                            mBLE.disconnect();
                        }
                        mBLE.connect(address);
                    }
                }
                break;

        }
    }
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    private void BleSei() {

        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
            finish();
        }
        blemHandler = new Handler();
        // Initializes a Bluetooth adapter.  For API level 18 and above, get a reference to
        // BluetoothAdapter through BluetoothManager.
        final BluetoothManager bluetoothManager =
                (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();

        // Checks if Bluetooth is supported on the device.
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        //open Bluetooth
        mBluetoothAdapter.enable();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                final AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("This app needs location access");
                builder.setMessage("Please grant location access so this app can detect Bluetooth.");
                builder.setPositiveButton(android.R.string.ok, null);
                builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                            requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
                        }
                    }
                });
                builder.show();
            }
        }

        mBLE = new BluetoothLeClass(this);
        if (!mBLE.initialize()) {
            finish();
        }

        //When Get data
        mBLE.setOnDataAvailableListener(mOnDataAvailable);
    }


    private BluetoothLeClass.OnDataAvailableListener mOnDataAvailable
            = new BluetoothLeClass.OnDataAvailableListener() {
        /**
         * BLE缁堢鏁版嵁琚鐨勪簨浠�
         */
        public void onCharacteristicRead(BluetoothGatt gatt,
                                         BluetoothGattCharacteristic characteristic, int status) {

        }

        /**
         * 鏀跺埌BLE缁堢鍐欏叆鏁版嵁鍥炶皟
         */
        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
        public void onCharacteristicWrite(BluetoothGatt gatt,
                                          BluetoothGattCharacteristic characteristic) {
   			/*Log.e(TAG,"onCharWrite "+gatt.getDevice().getName()
   					+" write "
   					+characteristic.getUuid().toString()
   					+" -> "
   					+new String(characteristic.getValue()));
   					*/
            byte[] buffer = characteristic.getValue();
            int bytes = buffer.length;
            byte[] strdata = new byte[bytes];
            int pStrdata = 0;
            for (int i = 0; i < bytes; i++) {
                if (buffer[i] == 0x2) pStrdata = 0;
                else if (buffer[i] == 0x0d) {
                    GetWeight(strdata);
                    pStrdata = 0;
                    //Log.e(TAG, "weight:"+scalenow.sformatNetWeight);
                    blemHandler.post(new Runnable() {

                        public void run() {
                            // TODO Auto-generated method stub
//                            scaleView.setUnit(scalenow.sUnit);
                            if (scalenow.bOverFlag) {
                                xiangweightEdit.setText("over----");
                            } else {
                                String[] strs = scalenow.sformatNetWeight.split(" ");
                                xiangweightEdit.setText(strs[strs.length - 1]);
                            }

                        }
                    });
                } else {
                    strdata[pStrdata] = buffer[i];
                    if (++pStrdata >= 30) pStrdata = 0;
                }


            }

        }
    };

    void GetWeight(byte[] databuf) {
        int i, j, offset = 6;
        boolean StartFalg = false;
        scalenow.bZeroFlag = true;
        scalenow.bOverFlag = false;
        scalenow.bWeiStaFlag = false;
        switch (databuf[0]) {
            case 'o':
            case 'O':
                scalenow.bOverFlag = true;
                break;
            case 'u':
            case 'U':
                scalenow.bWeiStaFlag = false;
                offset = 6;    //6
                break;
            case 's':
            case 'S':
                scalenow.bWeiStaFlag = true;
                break;
        }
        if (databuf[5] == '-') offset = 5;
        for (i = 0; i < 14; i++) {
            if (databuf[i + offset] == '\'') databuf[i + offset] = '.';
            if (StartFalg) {
                if (((databuf[i + offset] > '9') || (databuf[i + offset] < '.')) && (!((databuf[i + offset] == ' ') && (databuf[i + offset + 1] <= '9')))) {
                    break;
                }
            } else if ((databuf[i + offset] >= '0') && (databuf[i + offset] <= '9')) {
                StartFalg = true;
                if (databuf[i + offset] != '0') scalenow.bZeroFlag = false;
            }
        }
        scalenow.sformatNetWeight = new String(databuf, offset, i);


        for (j = 0; j < 6; j++) {
            if (databuf[i + j + offset] < 0x20) {
                break;
            }
        }
        scalenow.sUnit = new String(databuf, i + offset, j);

    }

    public static class SCALENOW {
        public String sformatNetWeight = "0";
        public String sUnit = "0";
        public boolean bWeiStaFlag;
        public boolean bZeroFlag;
        public boolean bOverFlag;
    }


    @Override
    protected void onPause() {
        super.onPause();
        runFlag = false;
        if (readerDevice != null) {
            readerDevice.powerOff();
        }
        if (mComFd > 0) {
            mCommonApi.setGpioOut(83, 0);
            mCommonApi.setGpioOut(78, 0);
            mCommonApi.closeCom(mComFd);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        // 注销获取扫描数据的广播
        unregisterReceiver(receiver);
        // 注销物理SCAN按键的接收广播
        unregisterReceiver(scanBroadcastReceiver);
        // unregisterReceiver(screenReceiver);
        closeGPIO();




    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }
}
